package com.rong.mbt.personal.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.calanger.hh.entity.ResultView;
import com.calanger.hh.model.Article;
import com.calanger.hh.model.Doctor;
import com.calanger.hh.model.OrderPre;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rong.mbt.personal.R;
import com.rong.mbt.personal.activity.ArticleDetailsActivity;
import com.rong.mbt.personal.activity.DoctorDetailsActivity;
import com.rong.mbt.personal.activity.PatientDetailActivity;
import com.rong.mbt.personal.adapter.FindDoctorListAdapter;
import com.rong.mbt.personal.adapter.FindDoctorListResultViewAdapter;
import com.rong.mbt.personal.adapter.IndexArticleListAdapter;
import com.rong.mbt.personal.adapter.IndexArticleListResultViewAdapter;
import com.rong.mbt.personal.adapter.IndexOrderListAdapter;
import com.rong.mbt.personal.bean.article.ArticleItemBean;
import com.rong.mbt.personal.bean.article.ArticleListPageBean;
import com.rong.mbt.personal.http.UrlApi;
import com.rong.mbt.personal.http.callback.JsonCallback;
import com.rong.mbt.personal.utils.SpUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;

/**
 * 文章列表
 */
public class SearchItemFragment extends Fragment implements OnRefreshLoadMoreListener {

    private String mTitle;
    private Integer userType = 0;
    private String searchContent;
    private RecyclerView mRecyclerView;
    private SmartRefreshLayout mRefreshLayout;
    private IndexArticleListResultViewAdapter articleListAdapter;
    private FindDoctorListResultViewAdapter findDoctorListAdapter;
    private IndexArticleListResultViewAdapter indexOrderListAdapter;
    private int pageNumber;
    private List<Map<String, Object>> initDataArticle = new ArrayList<Map<String, Object>>();
    private List<Map<String, Object>> initDataDoctor = new ArrayList<Map<String, Object>>();
    private List<Map<String, Object>> initDataOrderPre = new ArrayList<Map<String, Object>>();

    private int total_count_article = 0;
    private int total_count_doctor = 0;
    private int total_count_orderPre = 0;

    private boolean freshOrMore = false;
    private int selectedObjId;

    public static SearchItemFragment getInstance(String title, Integer userType, String searchContent) {
        SearchItemFragment sf = new SearchItemFragment();
        sf.mTitle = title;
        sf.userType = userType;
        sf.searchContent = searchContent;
        return sf;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        return super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_smart_refresh_layout, null);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRefreshLayout = view.findViewById(R.id.refreshLayout);

        mRefreshLayout.setOnRefreshLoadMoreListener(this);

        articleListAdapter = new IndexArticleListResultViewAdapter();
        findDoctorListAdapter = new FindDoctorListResultViewAdapter();
        indexOrderListAdapter = new IndexArticleListResultViewAdapter();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        if (mTitle.equals("文章")) {
            mRecyclerView.setAdapter(articleListAdapter);
        } else if (mTitle.equals("医生")) {
            mRecyclerView.setAdapter(findDoctorListAdapter);
        } else if (mTitle.equals("患者")) {
            mRecyclerView.setAdapter(indexOrderListAdapter);
        } else {
            Toast.makeText(getActivity(), "标题文章错误", Toast.LENGTH_SHORT);
        }

        articleListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Map<String, Object> item = (Map<String, Object>) adapter.getItem(position);
                JSONObject jo = new JSONObject(item);
                Article single = jo.getObject("article", Article.class);
                startActivity(new Intent(getActivity(), ArticleDetailsActivity.class).putExtra("id", single.getId()));
            }
        });
        findDoctorListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Map<String, Object> item = (Map<String, Object>) adapter.getItem(position);
                JSONObject jo = new JSONObject(item);
                Doctor single = jo.getObject("doctor", Doctor.class);
                startActivity(new Intent(getActivity(), DoctorDetailsActivity.class).putExtra("id", single.getId()));
            }
        });
        indexOrderListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Map<String, Object> item = (Map<String, Object>) adapter.getItem(position);
                JSONObject jo = new JSONObject(item);
                OrderPre single = jo.getObject("orderPre", OrderPre.class);
                startActivity(new Intent(getActivity(), PatientDetailActivity.class).putExtra("id", single.getId()));
            }
        });
        requestArticle();
    }

    private void requestArticle() {
        OkGo.<ResultView>get(UrlApi.searchList)
                .tag(this)
                .headers("mbtToken", SpUtils.getToken(getActivity()))
                .params("pageNumber", pageNumber)
                .params("keyword", searchContent)
                .execute(new JsonCallback<ResultView>() {
                    @Override
                    public void onSuccess(Response<ResultView> response) {
                        if (response != null && response.body() != null) {
                            ResultView resultView = response.body();
                            if (resultView.getData() != null && resultView.getResultCode() == 0) {
                                Map<String, Object> data = (Map<String, Object>) resultView.getData();
                                List<Map<String, Object>> resDataOrderPre = new ArrayList<Map<String, Object>>();
                                if (mTitle.equals("文章")) {

                                    JSONObject rv = new JSONObject(data);
                                    JSONObject articleRv = rv.getJSONObject("articleList");
                                    Integer count = articleRv.getObject("count",Integer.class);
                                    JSONArray ja = articleRv.getJSONArray("data");
                                    for(int i=0;i<ja.size();i++){
                                        JSONObject single = ja.getJSONObject(i);
                                        resDataOrderPre.add(single);
                                    }

                                    if (rv != null) {
                                        total_count_article = count;
                                        if (freshOrMore) {
                                            if (initDataArticle.size() >= total_count_article) {
                                                mRefreshLayout.finishLoadMore();
                                            } else {
                                                initDataArticle.addAll(resDataOrderPre);
                                            }
                                            freshOrMore = false;
                                            mRefreshLayout.finishLoadMore();
                                        } else {
                                            initDataArticle = resDataOrderPre;
                                            mRefreshLayout.finishRefresh();
                                        }
                                        articleListAdapter.setNewData(initDataArticle);
                                    }
                                } else if (mTitle.equals("医生")) {
//                                    ResultView rv = data.get("doctorList");

                                    JSONObject rv = new JSONObject(data);
                                    JSONObject articleRv = rv.getJSONObject("doctorList");
                                    Integer count = articleRv.getObject("count",Integer.class);
                                    JSONArray ja = articleRv.getJSONArray("data");
                                    for(int i=0;i<ja.size();i++){
                                        JSONObject single = ja.getJSONObject(i);
                                        resDataOrderPre.add(single);
                                    }

                                    if (rv != null) {
//                                        resDataOrderPre = (List<Map<String, Object>>) rv.getData();
                                        total_count_doctor = count;
                                        if (freshOrMore) {
                                            if (initDataDoctor.size() >= total_count_doctor) {
                                                mRefreshLayout.finishLoadMore();
                                            } else {
                                                initDataDoctor.addAll(resDataOrderPre);
                                            }
                                            freshOrMore = false;
                                            mRefreshLayout.finishLoadMore();
                                        } else {
                                            initDataDoctor = resDataOrderPre;
                                            mRefreshLayout.finishRefresh();
                                        }
                                        findDoctorListAdapter.setNewData(initDataDoctor);
                                    }
                                } else if (mTitle.equals("患者")) {
                                    JSONObject rv = new JSONObject(data);
                                    JSONObject articleRv = rv.getJSONObject("doctorList");
                                    Integer count = articleRv.getObject("count",Integer.class);
                                    JSONArray ja = articleRv.getJSONArray("data");
                                    for(int i=0;i<ja.size();i++){
                                        JSONObject single = ja.getJSONObject(i);
                                        resDataOrderPre.add(single);
                                    }
//                                    ResultView rv = data.get("orderPreList");
                                    if (rv != null) {
//                                        resDataOrderPre = (List<Map<String, Object>>) rv.getData();
                                        total_count_orderPre = count;
                                        if (freshOrMore) {
                                            if (initDataOrderPre.size() >= total_count_orderPre) {
                                                mRefreshLayout.finishLoadMore();
                                            } else {
                                                initDataOrderPre.addAll(resDataOrderPre);
                                            }
                                            freshOrMore = false;
                                            mRefreshLayout.finishLoadMore();
                                        } else {
                                            initDataOrderPre = resDataOrderPre;
                                            mRefreshLayout.finishRefresh();
                                        }
                                        indexOrderListAdapter.setNewData(initDataOrderPre);
                                    }
                                } else {
                                    Toast.makeText(getActivity(), "标题文章错误", Toast.LENGTH_SHORT);
                                }
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.finishLoadMore();
                            }
                        }
                    }
                });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        pageNumber++;
        freshOrMore = true;
        requestArticle();

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNumber = 1;
        requestArticle();
    }
}
